了解 Geometry (幾何體) 與 Material (材質) 後就可以開始組成物件了
先創建頭部及耳朵幾何體,並設定大小
const headGeo = new THREE.BoxGeometry(1.5, 1, 1);
const earGeo = new THREE.BoxGeometry(0.25, 0.75, 0.25);
載入臉部及耳朵圖案
const headTexture = new THREE.TextureLoader().load('images/Usagi_face.jpg')
const earTexture = new THREE.TextureLoader().load('images/Usagi_ear.jpg')
設定耳朵每一面同圖案,而臉部只有其中一面,不然會變六臉怪
const earMaterial = new THREE.MeshLambertMaterial({map:earTexture})
// 只設定一面有臉
const headMaterials = []
for (let i = 0; i < 6; i++) {
let map
if (i === 4) {
map = headTexture}
else {
map = earTexture
}
headMaterials.push(new THREE.MeshStandardMaterial({ map: map }))
}
調整頭部及耳朵到適當的位置,並創建一個Group,將頭部及耳朵透過 .add(object) 加入成為子對象,之後只要對 group 進行操作,就可以控制整個物件
//設定部位
this.head = new THREE.Mesh(headGeo,headMaterials)
this.head.position.set(0,0,0)
this.ear1 = new THREE.Mesh(earGeo,earMaterial)
this.ear1.position.set(-0.25,0.5,0)
this.ear2 = new THREE.Mesh(earGeo,earMaterial)
this.ear2.position.set(0.25,0.5,0)
// 組合
this.usagi = new THREE.Group()
this.usagi.add(this.head)
this.usagi.add(this.ear1)
this.usagi.add(this.ear2)
開啟陰影效果
this.usagi.traverse(function(object) {
if (object instanceof THREE.Mesh) {
object.castShadow = true
object.receiveShadow = true
}
})
組合好後就可以建立 function 生成物件並加入到場景
function createUsagi(){
usagiObj = new Usagi()
scene.add(usagiObj.usagi)
}
在 init() 裡呼叫 function 執行
//物件加入場景
createUsagi()
https://threejs.org/docs/?q=group#api/en/objects/Group